import { setPopup } from "@/ol-api/popup"
import { useTrafficStore } from "@/stores/counter";
import { createDraw } from "@/ol-api/createDraw"
import { Query } from '@/mapgis-api/Query'
import { markRaw } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { setAnimateStyle } from "@/api/ol-api/setAnimateStyle"
const { toggleUpdatePopupVisible, toggleAddPopupVisible } = useTrafficStore()

const trafficStore = useTrafficStore();
// 创建画笔
let addDraw = null
let updateDraw = null
let bufferDraw = null
// 创建画布
const addSource = new ol.source.Vector({})
const addLayer = new ol.layer.Vector({
    source: addSource
})
const updateSource = new ol.source.Vector({})
const updateLayer = new ol.layer.Vector({
    source: updateSource
})
const drawSource = new ol.source.Vector({})
const drawLayer = new ol.layer.Vector({
    source: drawSource
})
//事件点高亮数据源
const highlightSource = new ol.source.Vector({})

//添加事件
/**
 * 
 * @param {*ol.Map} $map 地图实例
 */
export const addEvent = ($map) => {
    //移除之前的画布
    $map.removeLayer(addLayer)
    $map.removeLayer(drawLayer)
    $map.removeLayer(updateLayer)
    //移除之前的图层
    $map.removeLayer(bufferLayer)
    //添加画布到地图
    $map.addLayer(addLayer)
    //清除之前的数据源和弹窗显示
    addSource.clear()
    updateSource.clear()
    highlightSource.clear()
    setPopup(null, $map)
    //清除之前的弹窗状态
    if (trafficStore.updatePopupVisible) {
        toggleUpdatePopupVisible()
    }
    //更改pinia中的弹窗状态
    if (!trafficStore.addPopupVisible) {
        toggleAddPopupVisible()
    }
    //移除之前的画笔和画布
    updateDraw && $map.removeInteraction(updateDraw);
    addDraw && $map.removeInteraction(addDraw);
    bufferDraw && $map.removeInteraction(bufferDraw);
    // 激活画笔并监听画笔结束事件
    addDraw = createDraw({ type: 'Point', source: addSource });
    addDraw && $map.addInteraction(addDraw);
    addDraw && addDraw.addEventListener('drawend', addDrawend.bind(null, addDraw, $map));
    // 将addSource存入pinia中
    trafficStore.addPopupSource = markRaw(addSource)

}
function addDrawend(addDraw, $map, evt) {
    $map.removeInteraction(addDraw);
    addSource.clear()
    //查询鼠标点击点是否有点要素
    let center = evt.feature.getGeometry().getCoordinates();
    trafficStore.eventPosition = center
    setPopup(center, $map)
    addDraw && addDraw.removeEventListener('drawend', addDrawend);
}
//更新事件
/**
 * 
 * @param {*ol.Map} $map 地图实例
 */
export const updateEvent = ($map) => {
    ElMessageBox.confirm(
        '请选择要更新的事件点',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'default',
        }
    ).then(() => {
        //移除之前的画布
        $map.removeLayer(addLayer)
        $map.removeLayer(drawLayer)
        $map.removeLayer(updateLayer)
        //移除之前的图层
        $map.removeLayer(bufferLayer)
        //添加画布到地图
        $map.addLayer(updateLayer)
        //清除之前的数据源和弹窗
        addSource.clear()
        updateSource.clear()
        setPopup(null, $map)
        //更改pinia中的弹窗状态
        if (trafficStore.addPopupVisible) {
            toggleAddPopupVisible()
        }
        if (!trafficStore.updatePopupVisible) {
            toggleUpdatePopupVisible()
        }
        //移除之前的画笔和画布
        updateDraw && $map.removeInteraction(updateDraw);
        addDraw && $map.removeInteraction(addDraw);
        bufferDraw && $map.removeInteraction(bufferDraw);

        //事件点高亮图层
        const highlightLayer = new ol.layer.Vector({
            source: highlightSource,
            style: setAnimateStyle({ map: $map, size: 40 })
        })
        //将高亮图层添加到地图中
        $map.addLayer(highlightLayer)
        //将高亮数据源存入pinia中
        trafficStore.highlightSource = markRaw(highlightSource)
        //查询当前点击的事件点的要素
        Query.queryByLayerId({
            service: {
                name: 'xm',
                layerId: 2
            },
            success: (features) => {
                //将所有要素添加到高亮图层中
                highlightSource.addFeatures(features)
            }
        })
        // 激活画笔并监听画笔结束事件
        updateDraw = createDraw({ type: 'Point', source: updateSource });
        $map.addInteraction(updateDraw);
        updateDraw && updateDraw.addEventListener('drawend', updateDrawend(updateDraw, $map));
        // 将updateSource存入pinia中
        trafficStore.updatePopupSource = markRaw(updateSource)
    })
    .catch(() => {
        ElMessage({
            message: '您取消了选择',
            type: 'info',
        })
    })
}



function updateDrawend(updateDraw, $map) {
    return (evt) => {
        //移除高亮图层,画笔,画笔数据源
        $map.removeInteraction(updateDraw);
        updateSource.clear()
        trafficStore.highlightSource.clear()
        //查询鼠标点击点是否有点要素
        let center = evt.feature.getGeometry().getCoordinates();
        trafficStore.eventPosition = center
        //设置service
        let service = { name: "xm", layerId: 2 }
        Query.queryByPnt({
            position: center,
            service,
            $map
        });
        updateDraw && updateDraw.removeEventListener('drawend', updateDrawend);
    }

}
//发布公告
//创建缓冲区数据源和图层
const bufferSource = new ol.source.Vector({
    features: []
})
const bufferLayer = new ol.layer.Vector({
    source: bufferSource,
    style: new ol.style.Style({
        fill: new ol.style.Fill({
            color: 'rgba(255, 0, 0, 0.5)'
        }),
        stroke: new ol.style.Stroke({
            color: 'red',
            width: 2
        })
    })
})
/**
 * 
 * @param {ol.Map} $map 地图实例
 */
export const addNotice = ($map) => {
    //移除之前的画布
    addLayer && $map.removeLayer(addLayer)
    updateLayer && $map.removeLayer(updateLayer)
    // 移除之前画布图层和缓冲区图层
    bufferLayer && $map.removeLayer(bufferLayer)
    drawLayer && $map.removeLayer(drawLayer)
    //将画布图层和缓冲区图层添加到地图中
    $map.addLayer(drawLayer)
    $map.addLayer(bufferLayer)
    //清除之前的数据源和弹窗
    addSource.clear()
    updateSource.clear()
    bufferSource.clear()
    highlightSource.clear()
    setPopup(null, $map)
    //更改pinia中的弹窗状态
    if (trafficStore.addPopupVisible) {
        toggleAddPopupVisible()
    }
    else if (trafficStore.updatePopupVisible) {
        toggleUpdatePopupVisible()
    }
    else if (trafficStore.watchNoticeVisible) {
        toggleWatchNoticeVisible()
    }
    //移除之前的画笔和画布
    bufferDraw && $map.removeInteraction(bufferDraw);
    updateDraw && $map.removeInteraction(updateDraw);
    addDraw && $map.removeInteraction(addDraw);
    // 激活画笔并监听画笔结束事件
    bufferDraw = createDraw({ type: 'LineString', source: drawSource });
    $map.addInteraction(bufferDraw);
    // 将bufferSource存入pinia中
    trafficStore.publicNoticeSource = markRaw(drawSource)
    bufferDraw && bufferDraw.addEventListener('drawend', bufferDrawend);
    console.log('发布公告')
}
// 监听画笔结束事件回调函数
function bufferDrawend(evt) {
    let center = evt.feature.getGeometry().getCoordinates()
    const lineBuffer = turf.lineString(center);
    // 创建线的缓冲区，第二个参数是缓冲区的半径（默认单位是度）这里改为米
    const bufferedLine = turf.buffer(lineBuffer, 100, { units: 'meters' });
    console.log(bufferedLine);
    // 将bufferedLine转化为ol要素的geometry对象中的要素
    const bufferedLineGeom = new ol.geom.Polygon(bufferedLine.geometry.coordinates)
    //查询缓冲区与居民区的交集
    Query.queryByGeometry({
        geometry: bufferedLineGeom,
        service: {
            name: 'xm',
            layerId: 0
        },
        success: (features) => {
            //清除数据
            // drawSource.clear()
            bufferSource.clear()
            // $map.removeInteraction(bufferDraw)
            if (features === null || features.length === 0) {
                ElMessage({
                    message: '当前范围内没有用户！',
                    type: 'warning',
                })
                // 清除画笔资源
                trafficStore.publicNoticeSource.clear()
                return
            } else {
                bufferSource.addFeatures(features)
                trafficStore.publicNoticeList = features.map((item) => {
                    const result = item.values_.values_
                    return {
                        name: result.name,
                        tel: result.tel
                    }
                })
                /* 弹出报告公告弹窗 */
                trafficStore.publicNoticeVisible = true
            }
        }
    })
}
//取消画笔
/**
 * 
 * @param {ol.Map} $map 地图实例
 */
export const removeBuffer = ($map) => {
    $map.removeInteraction(bufferDraw);
    bufferSource.clear()
    bufferLayer && $map.removeLayer(bufferLayer)
    drawLayer && $map.removeLayer(drawLayer)
    bufferDraw && bufferDraw.removeEventListener('drawend', bufferDrawend);

}
